<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input id="input" type="text" />
    <button id="button">1s只能点一次</button>
    <script>
      var input = document.getElementById("input");
      var button = document.getElementById("button");
      //设置全局变量实现防抖
      // let timer
      // input.onkeyup = function (e){
      //     const {value:keyWord} = e.target

      //     clearTimeout(timer)
      //     timer = setTimeout(() =>{
      //         console.log('过了一秒钟了',value)
      //     },1000)
      // }

      //   利用闭包实现
      function debounce(callBack, delay) {
        let debounceTimer = null; //保存timer一直再内存中不会每次都被重置，内存的泄露（内存减少）
        return function (e) {
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          debounceTimer = setTimeout(() => {
            callBack(e);
            debounceTimer = null;
          }, delay);
          //调用showValue ，如果不使用回调形式，会立刻执行showValue(e)
        };
      }
      //回调函数
      function showValue(event) {
        console.log(event.target.value);
      }
      //调用showValue ，如果不使用回调形式，会立刻执行showValue(e)
      input.onkeyup = debounce(showValue, 1000);

      /*
      节流
      */
      function throttling(callBack, delay) {
        let throttling = false;
        return function () {
          if (throttling) {
            return false;
          } else {
            throttling = true;
            setTimeout(() => {
              callBack();
              throttling = false;
            }, delay);
          }
        };
      }
      function showValue2() {
        console.log(Math.random());
      }
      button.onclick = throttling(showValue2, 1000);
    </script>
  </body>
</html>
